package com.pt25.base.dep.es;


import com.pt25.base.exception.BizException;
import com.pt25.base.util.StrUtil;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.*;

@Data
@Component
@ConfigurationProperties(prefix = "es-configs")
class EsProperties {

    /**
     * 默认集成名称
     */
    private String primary;

    private List<EsConfig> configs;

    @Data
    static class EsConfig {
        /**
         * es集群名称
         */
        private String name;
        /**
         * 集群地址
         */
        private String urls;
        /**
         * 用户名称
         */
        private String username;
        /**
         * 密码
         */
        private String password;
        /**
         * es版本
         */
        private String version;
        /**
         * 连接超时时间
         */
        private Integer connectTimeout = 1000;
        /**
         * socket超时时间
         */
        private Integer socketTimeout = 5000;
        /**
         * 最大连接数
         */
        private Integer maxConnTotal = 100;
        /**
         * 每路由最大连接数
         */
        private Integer maxConnPerRoute = 10;
        /**
         * 连接存活时间,单位：分钟
         */
        private Integer connectionTimeToLive = 1;


        @Override
        public String toString() {
            String[] urlsArr = urls.split(",");
            TreeSet<String> urlsTreeSet = new TreeSet<>(Arrays.asList(urlsArr));
            return "ESConfig{" +
                    "urls='" + urlsTreeSet + '\'' +
                    '}';
        }
    }

    Boolean checkConfigs() {
        Set<String> esNameSet = new HashSet<>();
        configs.forEach(config -> {
            esNameSet.add(config.getName());
            if (StrUtil.isBlank(config.getUrls())) {
                throw new BizException("urls is empty");
            }
            if (StrUtil.isBlank(config.getName())) {
                throw new BizException("name is empty");
            }
            if (StrUtil.isBlank(config.getVersion())) {
                throw new BizException("version is empty");
            }
            if (!"7".equals(config.getVersion()) && !"8".equals(config.getVersion())) {
                throw new BizException("version is not supported, only 7 or 8");
            }
        });
        if (esNameSet.size() != configs.size()) {
            throw new BizException("es集群名称有重复！");
        }
        return true;
    }
}
